package com.jph.simple;

import android.content.Intent;
import android.os.Bundle;


import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.google.protobuf.InvalidProtocolBufferException;

import container.ChatManager;
import socket.ServerSession;

import utgame.UtMessage.MS_PlayerChat;
import utgame.UtMessage.MessagePacket.MessageType;


public class MainActivity extends FragmentActivity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

    public static final String PARAM = "param";

    public static final String TAG = "MainActivity";

    private ImageView mIvAdd;
    private ImageView mIvMore;


    private ViewPager viewPager;// 声明一个viewpager对象

    private TextView[] tv = new TextView[3];

    private ImageView tabline;
    private List<Fragment> fragmentList;// 声明一个list集合存放Fragment（数据源）

    private int tabLineLength;// 1/3屏幕宽
    private int currentPage = 0;// 初始化当前页为0（第一页）

//    private Map<String, Handler> mFragmentHandlerMap = new HashMap<>();

    private boolean fragmentsUpdateFlag[] = new boolean[3];

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case MessageType.PlayerChat_VALUE:
                    try {
                        MS_PlayerChat chat = MS_PlayerChat.parseFrom((byte[])msg.obj);
                        ChatManager.getInstance().addChat(chat.getSenderName(), chat.getChatContent());

                        FriendFragment friendFragment = ((FriendFragment)fragmentList.get(1));
                        friendFragment.checkNewMessage();

                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    break;
                case MessageType.PlayerOnline_VALUE:
                case MessageType.PlayerOffline_VALUE:
                    FriendFragment friendFragment = ((FriendFragment)fragmentList.get(1));
                    friendFragment.updateUI();
                    break;
                case MessageType.GroupChat_VALUE:
                    HomeFragment homeFragment = (HomeFragment)fragmentList.get(0);
                    homeFragment.updateUI();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main_layout);

        currentPage = getIntent().getIntExtra(PARAM, 0);

        // 初始化滑动条1/3
        initTabLine();

        // 初始化界面
        initView();

        ServerSession.getInstance().addHandler(TAG, mHandler);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ServerSession.getInstance().removeHandler(TAG);

        // 如果放开这行，登陆会挂掉
//        fragmentList = null;
    }

    private void initTabLine() {
        // 获取显示屏信息
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        // 得到显示屏宽度
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        // 1/3屏幕宽度
        tabLineLength = metrics.widthPixels / 3;
        // 获取控件实例
        tabline = (ImageView) findViewById(R.id.tabline);
        // 控件参数
        LayoutParams lp = tabline.getLayoutParams();
        lp.width = tabLineLength;
        tabline.setLayoutParams(lp);
    }

    private void initView() {

        mIvAdd = (ImageView)findViewById(R.id.iv_top_add);
        mIvMore = (ImageView)findViewById(R.id.iv_top_more);

        mIvAdd.setOnClickListener(this);
        mIvMore.setOnClickListener(this);

        // 实例化对象
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tv[0] = (TextView) findViewById(R.id.tv1);
        tv[1] = (TextView) findViewById(R.id.tv2);
        tv[2] = (TextView) findViewById(R.id.tv3);

        for (int i = 0; i < tv.length; ++i){
            tv[i].setOnClickListener(this);
            tv[i].setTag(i);
        }

        fragmentList = new ArrayList<Fragment>();

        // 设置数据源
        final HomeFragment homeFragment = new HomeFragment();
        final FriendFragment friendFragment = new FriendFragment();
        SelfFragment selfFragment = new SelfFragment();

        fragmentList.add(homeFragment);
        fragmentList.add(friendFragment);
        fragmentList.add(selfFragment);

        // 设置适配器
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(
                getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return fragmentList.get(arg0);
//                if (arg0 == 0){
//                    HomeFragment fragment = new HomeFragment();
//                    fragmentList.set(0, fragment);
//                    return fragment;
//                } else {
//                    return fragmentList.get(arg0);
//                }
            }

//            @Override
//            public Object instantiateItem(ViewGroup container,int position) {
//
//                //得到缓存的fragment
//                Fragment fragment = (Fragment)super.instantiateItem(container, position);
//
//                //得到tag ❶
//                String fragmentTag = fragment.getTag();
//
////                if (fragmentsUpdateFlag[position %fragmentsUpdateFlag.length]) {
//                if (ChatManager.getInstance().isHomeReload){
//
//                    ChatManager.getInstance().isHomeReload = false;
//
//                    //如果这个fragment需要更新
//                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//
//                    //移除旧的fragment
//                    ft.remove(fragment);
//
//                    //换成新的fragment
//                    fragment = fragmentList.set(position % fragmentList.size(), new HomeFragment());
//
//                    //添加新fragment时必须用前面获得的tag ❶
//                    ft.add(container.getId(), fragment, fragmentTag);
//                    ft.attach(fragment);
//                    ft.commit();
//
//                    //复位更新标志
////                    fragmentsUpdateFlag[position %fragmentsUpdateFlag.length] =false;
//                }
//
//                return fragment;
//
//            }
        };

        // 绑定适配器
        viewPager.setAdapter(adapter);

        // 设置滑动监听
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // 当页面被选择时，先讲3个textview的字体颜色初始化成黑
                for (int i = 0; i < tv.length; ++i){
                    tv[i].setTextColor(Color.BLACK);
                }

                // 再改变当前选择页（position）对应的textview颜色
                switch (position) {
                    case 0:
                        tv[0].setTextColor(Color.rgb(51, 153, 0));
                        break;
                    case 1:
                        tv[1].setTextColor(Color.rgb(51, 153, 0));
                        break;
                    case 2:
                        tv[2].setTextColor(Color.rgb(51, 153, 0));
                        break;
                }

                currentPage = position;

            }

            // 滑动过程中调用：
            // 其中：arg0 :表示的当前屏幕显示的左边页面的position
            // arg1:表示的当前屏幕显示的左边页面偏移的百分比
            // arg2:表示的当前屏幕显示的左边页面偏移的像素位置

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.i("tuzi", position + "," + positionOffset + "," + positionOffsetPixels);

                // 取得该控件的实例
                LinearLayout.LayoutParams ll = (android.widget.LinearLayout.LayoutParams) tabline
                        .getLayoutParams();

                if (currentPage == 0 && position == 0) { // 0->1移动(第一页到第二页)
                    ll.leftMargin = (int) (currentPage * tabLineLength + positionOffset
                            * tabLineLength);
                } else if (currentPage == 1 && position == 1) { // 1->2移动（第二页到第三页）
                    ll.leftMargin = (int) (currentPage * tabLineLength + positionOffset
                            * tabLineLength);
                } else if (currentPage == 1 && position == 0) { // 1->0移动（第二页到第一页）
                    ll.leftMargin = (int) (currentPage * tabLineLength - ((1 - positionOffset) * tabLineLength));
                } else if (currentPage == 2 && position == 1) { // 2->1移动（第三页到第二页）
                    ll.leftMargin = (int) (currentPage * tabLineLength - (1 - positionOffset)
                            * tabLineLength);
                }

                tabline.setLayoutParams(ll);

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.tv1:
            case R.id.tv2:
            case R.id.tv3:
                // 设置ViewPager当前显示的页面,获得与icons[i]相同索引item(pager页面)
                viewPager.setCurrentItem((Integer) v.getTag());
                break;
            case R.id.iv_top_add:

                PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
                popupMenu.getMenuInflater().inflate(R.menu.menu_top_add, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(this);

                popupMenu.show();

                break;
        }

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.new_group:
                startActivity(new Intent(this, NewGroupActivity.class));
                finish();
                break;
            default:
                break;
        }
        return false;
    }

//    public void addHandler(String tag, Handler fragmentHandler){
//        mFragmentHandlerMap.put(tag, fragmentHandler);
//    }
//    public Handler getHandler(String tag){
//        return mFragmentHandlerMap.get(tag);
//    }

//    public boolean getFragmentsUpdateFlag(int index){
//        return fragmentsUpdateFlag[index];
//    }
//    public void setFragmentsUpdateFlag(int index){
//        fragmentsUpdateFlag[index] = true;
//    }

}